<template >
  <div style="margin: 10px 10px 10px 10px">
    <el-row class="title">全部评论（{{commentsCnt}}）
      <el-button type="text" @click="sortByMode(true)">最热</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-button type="text" @click="sortByMode(false)">最新</el-button>
    </el-row>
    <el-row class="comment-area">
      <el-col style="margin-right: 10px">
        <el-input type="textarea" v-model="inputComment" placeholder="请输入评论（字数少于100字）"></el-input>
      </el-col>
      <el-col style="flex: 1">
        <el-button plain type="primary" @click="send" class="item" :disabled="!inputComment">发布评论</el-button>
      </el-col>
    </el-row>
    <CommentDetail :comment="item" v-for="item in comments" :key="new Date().getTime()"></CommentDetail>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { getCommentsCountByPostId, getOneLevelCommentsByPostId, userSendComment } from "@/api/post/comment";
import CommentDetail from "@/components/comment/CommentDetail.vue";

export default {
  name: "CommentArea",
  inject: ['reload'],
  components: { CommentDetail },
  props: {
    postId: Number
  },
  data() {
    return {
      userId: 0,
      comments: {},
      inputComment: '',
      commentsCnt: 0,
      sortMode: true
    }
  },
  methods: {
    send() {
      userSendComment({
        content: this.inputComment,
        postId: this.postId,
        treeLevel: 1,
        userId: this.userId
      }).then(res => {
        if(res.data.code === 200) {
          this.reload()
          this.$message.success(res.data.message)
        } else {
          // this.$message.error(res.data.message)
        }
      })
    },
    getCommentList() {
      getOneLevelCommentsByPostId({
        postId: this.postId,
        isLikeNumberSort: this.sortMode
      }).then(res => {
        if(res.data.code === 200) {
          if(res.data.commentInfo !== null) {
            this.comments = res.data.oneLevelCommentList
          } else {
            this.comments = []
          }
        } else {
          // this.$message.error(res.data.message)
        }
      })
    },
    sortByMode(val) {
      this.sortMode = val;
      this.getCommentList()
    },
    getCommentsCount() {
      getCommentsCountByPostId({
        postId: this.postId
      }).then(res => {
        if(res.data.code === 200) {
          this.commentsCnt = res.data.count
        } else {
          // this.$message.error(res.data.message)
        }
      })
    }
  },
  created() {
    this.userId = JSON.parse(Cookies.get("user")).id
    this.getCommentList()
    this.getCommentsCount()
  },
  watch: {
    sortMode(newVal) {
      // console.log(1, newVal)
      this.getCommentList()
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  font-weight: bold;
  font-size: 14px;
  margin: 10px 0 10px 10px;
}

.comment-area {
  display: flex;
  align-items: center;
}

.item {
  height: 50px;
}

.left {
  margin-right: 10px;
}
</style>
